package com.malbbmsomanager.receipt;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.malbbmsomanager.DM_BBM_InvoiceMenu;
import com.malbbmsomanager.R;
import com.malbbmsomanager.adapter.DM_BBM_List_Adapters;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class DM_BBM_Bal_Receipt_Amt_Details extends Activity implements
		ActionBar.OnNavigationListener {

	private static final String TAG = null;
	LinearLayout dmreceiptlist, dmreceiptlistdetails;
	private DM_BBM_List_Adapters dbHelperReceiptList;
	private SimpleCursorAdapter dataAdapterReceipt;
	EditText myFilterCustomer, etheaderbalrecamt, etreceiptrefmanualno,
			etreceiptrefdate, etreceiptrefcurrency, etreceiptoriginalamt,
			etreceiptoutstandamt, etreceiptallocateamt, etreceiptrembalanceamt,
			etreceiptremarks, etreceiptgainloss, etheaderbalrecamtOriginal;
	String ReceiptRefNumber, CurrentReceiptRefNo, currentRepCode,Strusername,Strlrepprefix;
	// private PBDatabaseAdapter dbHelper;
	String preAllocatedAmount;
	Button selectreceiptrefno;

	BigDecimal RecOriAllocatedAmount = new BigDecimal("0.00");
	BigDecimal RecAllocatedAmount = new BigDecimal("0.00");
	BigDecimal RecBalanceAmount = new BigDecimal("0.00");

	BigDecimal CurrentAllocatingAmt = new BigDecimal("0.00");
	BigDecimal CurrentReceiptBalance = new BigDecimal("0.00");
	BigDecimal CurrentReceiptPendingAllocation = new BigDecimal("0.00");
	BigDecimal PrintCurrentReceiptBalance = new BigDecimal("0.00");
	BigDecimal PrintCurrentReceiptPendingAllocation = new BigDecimal("0.00");
	BigDecimal TotalAllocatedAmount = new BigDecimal("0.00");
	BigDecimal defaultAllocatedAmount = new BigDecimal("0.00");

	BigDecimal PreAllocatedReceiptAmount = new BigDecimal("0.00");
	private String DBNAME = "dminvoicemanagerbbm.db";
	private SQLiteDatabase mydb;
	// Receipt Tranactiob
	private String FPRECHED_TABLE = "FPRecHed";
	private String FPRECDET_TABLE = "FPRecDet";
	String MainReceiptRefNo,CurentRefNumber;
	int displayOption = 0; // CURRENT EDIT = 33
	
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat originalFormatDate = new SimpleDateFormat("MM dd yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyy");
	Date settingDate;
	
	
	public void btnCusListBack(View view) {
		dmreceiptlist.setVisibility(view.GONE);
		dmreceiptlistdetails.setVisibility(view.VISIBLE);
	}

	public void onclickUpdateContactInfo(View view) {
		String CurrentReceiptRef = selectreceiptrefno.getText().toString();
		// FPRECDET_TABLE
		// Check Previous Allocation Included
		if (etreceiptallocateamt.length() != 0) {
			BigDecimal BalanceAmount = new BigDecimal(etreceiptallocateamt
					.getText().toString().replaceAll("[,]", ""));
			int res;
			res = BalanceAmount.compareTo(defaultAllocatedAmount);
			if (res == 1) {
				Cursor checkReceiptDet = null;

				try {
					String querySelectDebtor = "SELECT * FROM FPRecDet WHERE RefNo = '"
							+ CurrentReceiptRefNo.trim()
							+ "' AND RefNo1 = '"
							+ CurrentReceiptRef + "'";
					checkReceiptDet = mydb.rawQuery(querySelectDebtor, null);
				} catch (Exception e) {
				}

				if (checkReceiptDet != null) {
					if (checkReceiptDet.getCount() > 0) {
						while (checkReceiptDet.moveToNext()) {
							BigDecimal PreAllocatedValue = new BigDecimal(
									"0.00");
							BigDecimal CurrentAllocatedValue = new BigDecimal(
									"0.00");
							BigDecimal TotalAllocatedValue = new BigDecimal(
									"0.00");
							/**** Current Allocation ****/
							String PreAllocatedValueStr = checkReceiptDet
									.getString(13);

							PreAllocatedValue = new BigDecimal(
									PreAllocatedValueStr.replaceAll("[,]", ""));
							CurrentAllocatedValue = new BigDecimal(
									etreceiptallocateamt.getText().toString()
											.trim().replaceAll("[,]", ""));

							/*TotalAllocatedValue = PreAllocatedValue
									.add(CurrentAllocatedValue);*/

							ContentValues updateReceiptAllocation = new ContentValues();
							updateReceiptAllocation.put("Amt", ""
									+ CurrentAllocatedValue);
							updateReceiptAllocation.put("BAmt", ""
									+ CurrentAllocatedValue);
							updateReceiptAllocation.put("AloAmt", ""
									+ CurrentAllocatedValue);
							mydb.update(FPRECDET_TABLE,
									updateReceiptAllocation, " RefNo = '"
											+ CurrentReceiptRefNo.trim()
											+ "' AND RefNo1 = '"
											+ CurrentReceiptRef + "'", null);

						}
					} else {

						try {
							Log.v(TAG, "Add Current Receipt Details");
							ContentValues add_Receipt_details = new ContentValues();
							add_Receipt_details.put("RefNo",
									CurrentReceiptRefNo);
							add_Receipt_details
									.put("RefNo1", CurrentReceiptRef);
							add_Receipt_details.put("SaleRefNo", currentRepCode);
							add_Receipt_details.put("ManuRef",
									etreceiptrefmanualno.getText().toString());
							add_Receipt_details.put("TxnType", "40");
							add_Receipt_details.put("TxnDate", getAddTaxnDate()
									.toString());
							add_Receipt_details.put("DtxnDate",
									etreceiptrefdate.getText().toString());
							add_Receipt_details.put("DtxnType", "10");
							add_Receipt_details.put("DCurCode",
									etreceiptrefcurrency.getText().toString());
							add_Receipt_details.put("DCurRate", "1.0");
							add_Receipt_details.put("OCurRate", "1.0");
							add_Receipt_details.put("RepCode", currentRepCode);
							
							BigDecimal AmountValue = new BigDecimal(etreceiptallocateamt.getText().toString().trim().replaceAll("[,]", ""));
							AmountValue = AmountValue.setScale(2,BigDecimal.ROUND_HALF_DOWN);
							add_Receipt_details.put("Amt","" + AmountValue);
							add_Receipt_details.put("BAmt","" + AmountValue);
							add_Receipt_details.put("GainLosAmt", "0.0000");
							add_Receipt_details.put("BnkChgs", "0.0000");
							add_Receipt_details.put("BBnkChgs", "0.00");
							add_Receipt_details.put("AloAmt",
									etreceiptallocateamt.getText().toString());
							add_Receipt_details.put("OvPayAmt", "0.0000");
							add_Receipt_details.put("OvPayBal", "0.0000");
							add_Receipt_details.put("SyncState", "0");
							
							mydb.insert(FPRECDET_TABLE, null,
									add_Receipt_details);
						} catch (Exception e) {
							Log.v(TAG, "Exception : " + e);
						}

					}
				}
				else{
					addFail();
				}

				mydb.close();
				updateHeaderDetails();
				addSuccess();
			} else {

				addFail();
			}
		}

		else {
			addFail();
		}

	}

	private void addFail() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_BBM_Bal_Receipt_Amt_Details.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("INVALID ALLOCATION");
		// Setting Dialog Message
		alertDialog
				.setMessage("Please Enter Valid Receipt Amount To Allocate Values");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	private void updateHeaderDetails() {
		// TODO Auto-generated method stub

		// Receipt Header Update
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		ContentValues add_Receipt_Hed_Update = new ContentValues();
		add_Receipt_Hed_Update.put("AllocatedAmount", etheaderbalrecamt
				.getText().toString());
		mydb.update(FPRECHED_TABLE, add_Receipt_Hed_Update, "RefNo ='"
				+ CurrentReceiptRefNo + "'", null);
	}

	private void addSuccess() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_BBM_Bal_Receipt_Amt_Details.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("RECEIPT UPDATE");
		// Setting Dialog Message
		alertDialog.setMessage("Receipt Amount Allocated Successfully");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				BackAction();
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		return;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_bal_receipt_amt_details);
		dmreceiptlist = (LinearLayout) findViewById(R.id.dmreceiptlist);
		dmreceiptlistdetails = (LinearLayout) findViewById(R.id.dmreceiptlistdetails);
		myFilterCustomer = (EditText) findViewById(R.id.dminvfilterreceipts);
		etheaderbalrecamt = (EditText) findViewById(R.id.etheaderbalrecamt);
		selectreceiptrefno = (Button) findViewById(R.id.selectreceiptrefno);
		etreceiptrefmanualno = (EditText) findViewById(R.id.etreceiptrefmanualno);
		etreceiptrefdate = (EditText) findViewById(R.id.etreceiptrefdate);
		etreceiptrefcurrency = (EditText) findViewById(R.id.etreceiptrefcurrency);
		etreceiptoriginalamt = (EditText) findViewById(R.id.etreceiptoriginalamt);
		etreceiptoutstandamt = (EditText) findViewById(R.id.etreceiptoutstandamt);
		etreceiptallocateamt = (EditText) findViewById(R.id.etreceiptallocateamt);
		etreceiptallocateamt
				.addTextChangedListener(calculateBalanceAmountReceived);
		etreceiptrembalanceamt = (EditText) findViewById(R.id.etreceiptrembalanceamt);
		etreceiptremarks = (EditText) findViewById(R.id.etreceiptremarks);
		etreceiptgainloss = (EditText) findViewById(R.id.etreceiptgainloss);
		etheaderbalrecamtOriginal = (EditText) findViewById(R.id.etheaderbalrecamtOriginal);

		dbHelperReceiptList = new DM_BBM_List_Adapters(this);
		dbHelperReceiptList.open();

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			MainReceiptRefNo = extras.getString("TAGID");
			CurentRefNumber = extras.getString("TAGIDREF");
		}

		selectreceiptrefno.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				etheaderbalrecamt.setText("" + RecBalanceAmount);
				dmreceiptlist.setVisibility(view.VISIBLE);
				dmreceiptlistdetails.setVisibility(view.GONE);
			}
		});

		/* Check Selected Receipt Already Allocated with a Value */
		checkDisplayMode();
		getCurrentUser();
	}

	// Get the current Users From DB
		private void getCurrentUser() {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			String querygetuser;
			Cursor curgetuser = null;
			try {
				querygetuser = "SELECT * from usersettings";
				curgetuser = mydb.rawQuery(querygetuser, null);
			} catch (Exception e) {

			}
			
			if (curgetuser != null) {
				if (curgetuser.getCount() > 0) {
					while (curgetuser.moveToNext()) {
						Strusername = curgetuser.getString(1);
						Strlrepprefix = curgetuser.getString(2);
						if (Strlrepprefix != null) {
							Strlrepprefix = curgetuser.getString(2);
						} else {
							Strlrepprefix = "A";
						}
					}
				}
			}
		}

	private void checkDisplayMode() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curCheckAllocate = null;

		try {
			String querySelectDebtor = "SELECT * FROM FPRecDet WHERE RefNo1 = '"
					+ MainReceiptRefNo.trim() + "' AND RefNo = '" + CurentRefNumber + "'";
			curCheckAllocate = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}

		if (curCheckAllocate != null) {
			if (curCheckAllocate.getCount() > 0) {
				while (curCheckAllocate.moveToNext()) {
					Log.v(TAG, "Previously Allocated : " + MainReceiptRefNo);
					displayOption = 33;
					preAllocatedAmount = curCheckAllocate.getString(18);
					DisplayHeaderAmountPreAlloate();

				}
			} else {
				Log.v(TAG, "New Allocation : " + MainReceiptRefNo);
				DisplayHeaderAmount();
				getLoadReceiptDetails();
			}
		}

	}

	/***** Reset Header Amount to display *****/
	private void DisplayHeaderAmountPreAlloate() {
		// TODO Auto-generated method stub
		PreAllocatedReceiptAmount = new BigDecimal(
				preAllocatedAmount.replaceAll("[,]", ""));

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor CurFPRecHed = null;
		try {
			String queryChkSalesOrder = "SELECT * FROM FPRecHed WHERE ActiveState ='1'";
			CurFPRecHed = mydb.rawQuery(queryChkSalesOrder, null);

		} catch (Exception e) {
		}
		if (CurFPRecHed != null) {
			if (CurFPRecHed.getCount() > 0) {
				while (CurFPRecHed.moveToNext()) {

					CurrentReceiptRefNo = CurFPRecHed.getString(1);
					currentRepCode = CurFPRecHed.getString(4);
					String AllocatedTotal = CurFPRecHed.getString(42);
					String ReceiptsAllocatedTotal = CurFPRecHed.getString(43);

					//Total Allocated Amount
					RecOriAllocatedAmount = new BigDecimal(AllocatedTotal.replaceAll("[,]", ""));
					//Current Total Allocated For Receipt
					RecAllocatedAmount = new BigDecimal(ReceiptsAllocatedTotal.replaceAll("[,]", ""));
					//Current Total Allocated For Receipt except for Selected Receipt
					BigDecimal PendingAllocation = RecAllocatedAmount.add(PreAllocatedReceiptAmount);
					
					etheaderbalrecamt.setText("" + PendingAllocation);
					etheaderbalrecamtOriginal.setText("" + PendingAllocation);
				
				}
			}
		}
		getLoadReceiptDetails();
	}

	private void getLoadReceiptDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListReceiptDetails = null;

		try {
			String querySelectDebtor = "SELECT * FROM fddbnote WHERE RefNo = '"
					+ MainReceiptRefNo.trim() + "'";
			curListReceiptDetails = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}

		if (curListReceiptDetails != null) {
			if (curListReceiptDetails.getCount() > 0) {
				while (curListReceiptDetails.moveToNext()) {
					String record_0 = curListReceiptDetails.getString(0);// index
					String record_1 = curListReceiptDetails.getString(1);// RefNo
					String record_2 = curListReceiptDetails.getString(2);// TxnDate
					String record_3 = curListReceiptDetails.getString(3);// BAmt
					String record_4 = curListReceiptDetails.getString(4);// DebCode
					String record_5 = curListReceiptDetails.getString(5);// RecordId
					String record_6 = curListReceiptDetails.getString(6);// ManuRef
					String record_7 = curListReceiptDetails.getString(7);// Curcode
					String record_8 = curListReceiptDetails.getString(8);// Amt
					String record_9 = curListReceiptDetails.getString(9);// Totbal
					String record_10 = curListReceiptDetails.getString(10);// Remarks
					String record_11 = curListReceiptDetails.getString(11);// RepCode
					Log.v(TAG, "Txn Date :" + record_2);
					String[] PrintDateArray = record_2.split(" ");
					/**** this will contain Date Part ****/
					String PrintDate = PrintDateArray[0];
					Log.v(TAG, "PrintDate 1:" + PrintDate);
					selectreceiptrefno.setText(record_1);
					etreceiptrefmanualno.setText(record_6);
					try {
						settingDate = originalFormatDate.parse(PrintDate.replaceAll("[-+/.^:,]", " "));
						PrintDate = targetFormat.format(settingDate);
						Log.v(TAG, "PrintDate 2:" + PrintDate);
					} catch (ParseException ex) {
						PrintDate = getAddTaxnDate().toString();
					}
					etreceiptrefdate.setText(PrintDate);
					etreceiptrefcurrency.setText(record_7);
					etreceiptoriginalamt.setText(record_8);

					String FPRDrecord_12 = "0.00";
					BigDecimal StrTotalAllocatedAmount = new BigDecimal("0.00");
					Cursor curFPRecDet = null;
					try {
						String querySelectcurFPRecDet = "SELECT * FROM FPRecDet WHERE RefNo1 = '"
								+ record_1.trim() + "' AND RefNo = '"+ CurrentReceiptRefNo.trim() +"'";
						curFPRecDet = mydb.rawQuery(querySelectcurFPRecDet,
								null);
					} catch (Exception e) {
					}
					if (curFPRecDet != null) {
						if (curFPRecDet.getCount() > 0) {
							while (curFPRecDet.moveToNext()) {
								// Allocated Amount gggg

								try {
									FPRDrecord_12 = curFPRecDet.getString(13);// Amt
									StrTotalAllocatedAmount = new BigDecimal(
											FPRDrecord_12.replaceAll("[,]", ""));
									TotalAllocatedAmount = TotalAllocatedAmount
											.add(StrTotalAllocatedAmount);
								} catch (Exception e) {
									TotalAllocatedAmount = new BigDecimal(
											"0.00");
								}

							}
						}
					}
					BigDecimal StrTotalPendingAmount = new BigDecimal(
							record_9.replaceAll("[,]", ""));
					BigDecimal BalanceAmount = StrTotalPendingAmount
							.subtract(StrTotalAllocatedAmount);
					if (displayOption == 33) {
						etreceiptallocateamt.setText("0.00");
						
						etreceiptoutstandamt.setText("" + BalanceAmount.add(PreAllocatedReceiptAmount));
						etreceiptrembalanceamt.setText("" + BalanceAmount.add(PreAllocatedReceiptAmount));
						etreceiptremarks.setText(record_10);
						/*etreceiptoutstandamt.setText(""
								+ BalanceAmount.add(PreAllocatedReceiptAmount));
						etreceiptrembalanceamt.setText(""
								+ BalanceAmount.add(PreAllocatedReceiptAmount));*/
						etreceiptremarks.setText(record_10);
					} else {
						etreceiptoutstandamt.setText("" + BalanceAmount);
						etreceiptrembalanceamt.setText("" + BalanceAmount);
						etreceiptremarks.setText(record_10);
					}

				}
			}
		}
	}

	private void DisplayHeaderAmount() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor CurFPRecHed = null;
		try {
			String queryChkSalesOrder = "SELECT * FROM FPRecHed WHERE ActiveState ='1'";
			CurFPRecHed = mydb.rawQuery(queryChkSalesOrder, null);

		} catch (Exception e) {
		}
		if (CurFPRecHed != null) {
			if (CurFPRecHed.getCount() > 0) {
				while (CurFPRecHed.moveToNext()) {
					CurrentReceiptRefNo = CurFPRecHed.getString(1);
					currentRepCode = CurFPRecHed.getString(4);
					String AllocatedTotal = CurFPRecHed.getString(42);
					String ReceiptsAllocatedTotal = CurFPRecHed.getString(43);

					RecOriAllocatedAmount = new BigDecimal(
							AllocatedTotal.replaceAll("[,]", ""));
					RecAllocatedAmount = new BigDecimal(
							ReceiptsAllocatedTotal.replaceAll("[,]", ""));

					int res;
					res = RecOriAllocatedAmount.compareTo(RecAllocatedAmount);
					if (res == 0) {
						etheaderbalrecamt.setText("" + RecOriAllocatedAmount);
						etheaderbalrecamtOriginal.setText(""
								+ RecOriAllocatedAmount);
					} else {
						RecBalanceAmount = RecOriAllocatedAmount
								.subtract(RecAllocatedAmount);
						RecBalanceAmount = RecBalanceAmount.setScale(2,
								BigDecimal.ROUND_HALF_DOWN);
						etheaderbalrecamt.setText("" + RecAllocatedAmount);
						etheaderbalrecamtOriginal.setText(""
								+ RecAllocatedAmount);
					}
				}
			}
		}

	}



	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			BackAction();
			return true;
		case R.id.action_refresh:
			// refresh
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void BackAction() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_Bal_Receipt_Amt_Details.this,
				DM_BBM_InvoiceSalesReceipt.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	private TextWatcher calculateBalanceAmountReceived = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			String ReceiptBalance = "0.00";
			String ReceiptPendingAllocation = "0.00";
			Log.v(TAG, "afterTextChanged 1");
			if (etreceiptallocateamt.length() != 0) {

				// Current Invoice Values
				if (etreceiptoutstandamt.length() != 0) {
					ReceiptBalance = etreceiptoutstandamt.getText().toString();
					CurrentReceiptPendingAllocation = new BigDecimal(
							ReceiptBalance.replaceAll("[,]", ""));
				}
				// Main Receipt Balance Amount
				if (etheaderbalrecamtOriginal.length() != 0) {
					ReceiptPendingAllocation = etheaderbalrecamtOriginal
							.getText().toString();
					PrintCurrentReceiptBalance = new BigDecimal(
							ReceiptPendingAllocation.replaceAll("[,]", ""));
				}

				CurrentAllocatingAmt = new BigDecimal(etreceiptallocateamt
						.getText().toString());

				int res;
				res = PrintCurrentReceiptBalance
						.compareTo(CurrentAllocatingAmt); // compare bg1 with
															// bg2

				if (res == 1 || res == 0) {
					Log.v(TAG, "First Value is greater");
					int resRec;
					resRec = CurrentReceiptPendingAllocation
							.compareTo(CurrentAllocatingAmt); // compare bg1
																// with bg2
					if (resRec == -1) {
						Log.v(TAG, "Second Value is greater");
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_BBM_Bal_Receipt_Amt_Details.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("INVALID AMOUNT");
						// Setting Dialog Message
						alertDialog
								.setMessage("Allocating Amount Exceed Selected Receipt Balance Amount.");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										etreceiptallocateamt.setText("0.00");
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {

						Log.v(TAG, "Outst  Amt:" + ""
								+ CurrentReceiptPendingAllocation);
						Log.v(TAG, "Alloc  Amt:" + "" + CurrentAllocatingAmt);
						Log.v(TAG, "Header Amt:" + "" + PrintCurrentReceiptBalance);

						BigDecimal PrintCurrentReceiptBalanceItem = CurrentReceiptPendingAllocation
								.subtract(CurrentAllocatingAmt);
						PrintCurrentReceiptPendingAllocation = PrintCurrentReceiptBalance
								.subtract(CurrentAllocatingAmt);

						etreceiptrembalanceamt.setText(""
								+ PrintCurrentReceiptBalanceItem);
						etheaderbalrecamt.setText(""
								+ PrintCurrentReceiptPendingAllocation);
					}
				} else if (res == -1) {
					Log.v(TAG, "Second Value is greater");

					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_BBM_Bal_Receipt_Amt_Details.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("INVALID AMOUNT");
					// Setting Dialog Message
					alertDialog
							.setMessage("Allocating Amount Exceed Receipt Balance Amount.");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									etreceiptallocateamt.setText("0.00");
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}

			} else {
				etreceiptallocateamt.setText("0.00");
				CurrentAllocatingAmt = new BigDecimal("0.00");
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.v(TAG, "beforeTextChanged");
			CurrentAllocatingAmt = new BigDecimal("0.00");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onTextChanged");
			CurrentAllocatingAmt = new BigDecimal("0.00");
		}

	};

	private String getAddTaxnDate() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("dd/MM/yyyy");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
	
	
}
